﻿using HaiSpider.Component.Http;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using 易发车网.Untils;
using 易发车网.WebResult;

namespace 易发车网.WebSpider
{
    /// <summary>
    /// 网站
    /// </summary>
    public class _28CarApi
    {
        #region 字段 & 变量
        private const string UrlIndex = "https://m.28car.com/sell_lst.php";         // 首页信息
        private const string UrlDetial = "https://m.28car.com/sell_dsp.php?h_vid="; // 详情
        private const string PostData_Filter = "h_f_ty=1&h_f_yr={0}&h_f_do=1&h_page={1}"; // 查询数据
        private const string PostData_Phohe = "h_srh={0}&h_srh_ty=4";
        #endregion


        #region 公开方法
        /// <summary>
        /// 读取汽车列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public async Task<List<SellInfo>> GetSellList(int page,int year)
        {
            // Console.WriteLine("page:" + page);
            var client = HaiHttp.CreateDefaultHttpClient();
            var request = HaiHttp.CreateDefaultPostRequest(UrlIndex);
            request.Content = new StringContent(CreateFilterPostData(page,year),Encoding.UTF8,HaiHttp.H_Content_Type);
            var response = await client.SendAsync(request);
            if (!response.IsSuccessStatusCode)
            {
                return null;
            }
            var byteStream = await response.Content.ReadAsStreamAsync();

            var html = new StreamReader(byteStream, Encoding.GetEncoding("Big5")).ReadToEnd();
            html = html.Replace("charset=big5", "charset=gbk2312");
            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var list = doc.DocumentNode.SelectSingleNode("//*[@id='tch_box']/table");
            if (list != null)
            {
                var result = new List<SellInfo>();
                var length = list.Elements("tr").ToList().Count;
                for (int i = 0; i < length - 1; i++)
                {
                    var carname = doc.DocumentNode.SelectSingleNode($"//*[@id='rw_{i}']/table/tr/td[1]/table/tr[1]/td[1]").InnerText.Replace("&nbsp;", " ");
                    var carid = doc.DocumentNode.SelectSingleNode($"//*[@id='rw_{i}']/table/tr/td[1]").Attributes["onclick"].Value.Split(',')[1].Trim();
                    var viewCount = doc.DocumentNode.SelectSingleNode($"//*[@id='rw_{i}']/table/tr/td[1]/table/tr[1]/td[9]/font").InnerText;
                    var info = new SellInfo()
                    {
                        CarName = carname,
                        Vid = carid,
                        ViewCount = int.Parse(viewCount)
                    };
                    result.Add(info);
                }
                return result;
            }
            return null;
        }

        /// <summary>
        /// 搜索手机号下的车数量
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public async Task<int> GetSellListByPhone(string phone)
        {
            var client = HaiHttp.CreateDefaultHttpClient();
            var request = HaiHttp.CreateDefaultPostRequest(UrlIndex);
            request.Content = new StringContent(CreatePhonePostData(phone), Encoding.UTF8, HaiHttp.H_Content_Type);
            var response = await client.SendAsync(request);
            if (!response.IsSuccessStatusCode)
            {
                return 0;
            }
            var byteStream = await response.Content.ReadAsStreamAsync();

            var html = new StreamReader(byteStream, Encoding.GetEncoding("Big5")).ReadToEnd();
            html = html.Replace("charset=big5", "charset=gbk2312");
            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var list = doc.DocumentNode.SelectSingleNode("//*[@id='tch_box']/table");
            if (list != null)
            {
                return list.Elements("tr").Count() - 1;
            }
            return 0;
        }

        /// <summary>
        /// 根据Vid获取详情
        /// </summary>
        /// <param name="vid"></param>
        /// <returns></returns>
        public async Task<SellDetial> GetPhoneByVid(string vid)
        {
            var client = HaiHttp.CreateDefaultHttpClient();
            var request = HaiHttp.CreateDefaultGetRequest($"{UrlDetial}{vid}");
            var response = await client.SendAsync(request);
            if (!response.IsSuccessStatusCode)
            {
                return null;
            }
            var byteStream = await response.Content.ReadAsStreamAsync();

            var html = new StreamReader(byteStream, Encoding.GetEncoding("Big5")).ReadToEnd();
            html = html.Replace("charset=big5", "charset=gbk2312");
            var doc = new HtmlDocument();
            doc.LoadHtml(html);

            // 采集信息
            var detialInfo = new SellDetial();
            detialInfo.Url = $"{UrlDetial}{vid}";

            // 车子图片
            var ele_img = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[1]/td[3]/table[1]/tr/td/table/tr/td/a/img");
            if (ele_img != null)
            {
                detialInfo.ImgUrl = ele_img.Attributes["src"].Value.Replace("_m","_b");
            }
            // 编号
            var ele_num = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[1]/td[2]/b");
            if (ele_num != null)
            {
                detialInfo.SellNum = ele_num.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_num.InnerText.Replace("&nbsp;",""));
            }

            // 车类型
            var ele_cartype = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[4]/td[2]/a/b");
            if (ele_cartype != null)
            {
                detialInfo.CarType = ele_cartype.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_cartype.InnerText.Replace("&nbsp;", ""));
            }

            // 车厂
            var ele_carfactory = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[3]/td[2]");
            if (ele_carfactory != null)
            {
                detialInfo.CarBrand = ele_carfactory.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_carfactory.InnerText.Replace("&nbsp;", ""));
            }

            // 车型号
            var ele_carmodel = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[4]/td[2]/a/b");
            if (ele_carmodel != null)
            {
                detialInfo.Model = ele_carmodel.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_carmodel.InnerText.Replace("&nbsp;", ""));
            }

            // 座位
            var ele_seat = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[5]/td[2]");
            if (ele_seat != null)
            {
                detialInfo.Seat = ele_seat.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_seat.InnerText.Replace("&nbsp;", ""));
            }

            // 容积
            var ele_volume = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[6]/td[2]");
            if (ele_volume != null)
            {
                detialInfo.Volume = ele_volume.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_volume.InnerText.Replace("&nbsp;", ""));
            }

            // 容积
            var ele_transmission = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[7]/td[2]");
            if (ele_transmission != null)
            {
                detialInfo.Transmission = ele_transmission.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_transmission.InnerText.Replace("&nbsp;", ""));
            }

            // 年份
            var ele_year = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[8]/td[2]");
            if (ele_year != null)
            {
                detialInfo.Year = ele_year.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_year.InnerText.Replace("&nbsp;", ""));
            }

            // 简评
            var ele_title = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[9]/td[2]");
            if (ele_title != null)
            {
                detialInfo.Title = ele_title.InnerText.Replace("&nbsp;", "").Trim();
                // Console.WriteLine(ele_title.InnerText.Replace("&nbsp;", "").Replace("\n","").Trim());
            }

            // 售价
            var ele_price = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[10]/td[2]");
            if (ele_price != null)
            {
                var t_str = ele_price.InnerText.Replace("&nbsp;", "").Replace("\r\n","").Replace("\n","").Trim();
                if(t_str.Split('[').Length == 1)
                {
                    detialInfo.Price = double.Parse(t_str.Replace("HKD$", "").Trim(','));
                    detialInfo.OriginPrice = detialInfo.Price;
                    detialInfo.Discount = 0;
                }
                else
                {
                    var x = t_str.Split('[');
                    detialInfo.Price = double.Parse(t_str.Split('[')[0].Replace("HKD$", "").Trim(','));
                    detialInfo.OriginPrice = double.Parse(t_str.Split('[')[1].Replace("原價$", "").Replace("]","").Trim(','));
                    detialInfo.Discount = detialInfo.OriginPrice - detialInfo.Price;
                }
                // Console.WriteLine($"售价:{detialInfo.Price},原价:{detialInfo.OriginPrice},折扣:{detialInfo.Discount}");
            }

            // 电话
            var ele_phone = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[11]/td[2]");
            if (ele_phone != null)
            {
                if (ele_phone.InnerText.Contains("電話"))
                {
                    detialInfo.Tel = ele_phone.InnerText.Split(':').ToList().LastOrDefault();
                }
                else if (ele_phone.InnerText.Contains("電郵"))
                {
                    detialInfo.Tel = ele_phone.InnerText.Split(':').ToList().LastOrDefault();
                }
            }

            // 更新日期
            var ele_updatetime = doc.DocumentNode.SelectSingleNode("/html/body/table[6]/tr/td/table/tr/td/table/tr/td/table[3]/tr/td/table/tr[12]/td[2]");
            if (ele_updatetime != null)
            {
                detialInfo.UpdateTime = ele_updatetime.InnerText.Replace("&nbsp;", "");
                // Console.WriteLine(ele_updatetime.InnerText.Replace("&nbsp;", ""));
            }

            return detialInfo;
        }
        #endregion


        #region 私有方法
        /// <summary>
        /// 创建请求内容
        /// </summary>
        /// <param name="page"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        private string CreateFilterPostData(int page,int year)
        {
            return string.Format(PostData_Filter, DateTime.Now.Year - year + 1, page);
        }


        /// <summary>
        /// 搜索手机号
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        private string CreatePhonePostData(string phone)
        {
            return string.Format(PostData_Phohe, phone);
        }
        #endregion
    }
}
